package com.example.weddingapp.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.lifecycle.AndroidViewModel;


import com.example.weddingapp.R;
import com.example.weddingapp.base.BaseActivity;
import com.example.weddingapp.databinding.ActivityRegisterBinding;

import cn.leancloud.AVUser;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @Date 2020/4/20 21:02
 * @Desc 注册
 */

public class RegisterActivity extends BaseActivity<AndroidViewModel, ActivityRegisterBinding> implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

    }

    @Override
    protected void initView() {
        super.initView();
        showContentView();
        setTitle("注册");
        bindingView.btnRegister.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        //账号
        String username = bindingView.etUsername.getText().toString();
        //密码
        String password = bindingView.etPassword.getText().toString();
        //确认密码
        String confirmPassword = bindingView.etRePassword.getText().toString();

        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!password.equals(confirmPassword)) {
            Toast.makeText(this, "密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }
        // 创建实例
        AVUser user = new AVUser();

        // 等同于 user.put("username", "Tom")
        user.setUsername(username);
        user.setPassword(password);
        //注册提交
        user.signUpInBackground().subscribe(new Observer<AVUser>() {
            public void onSubscribe(Disposable disposable) {
                hud.show();
            }

            public void onNext(AVUser user) {
                hud.dismiss();
                // 注册成功
                Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                System.out.println("注册成功。objectId：" + user.getObjectId());
                finish();
            }

            public void onError(Throwable throwable) {
                hud.dismiss();
                // 注册失败（通常是因为用户名已被使用）
                Toast.makeText(RegisterActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
            }

            public void onComplete() {
            }
        });
    }
}
